#include "gameview.h"
#include "qtimer.h"

//GameView::GameView(){}

GameView::GameView(QWidget *parent):QGraphicsView(parent)
{
    qreal scaleFactor =2.0;
    this->scale(scaleFactor, scaleFactor);
    // 启用平滑缩放
    this->setRenderHint(QPainter::Antialiasing);
    this->setRenderHint(QPainter::SmoothPixmapTransform);
    setEnabled(true);
    setFocusPolicy(Qt::StrongFocus);//确保能够设定焦点在gameview中
    gameviewkeytimer=new QTimer(this);
    gameviewkeytimer->start(50);
    connect(gameviewkeytimer,&QTimer::timeout,this,&GameView::keyupdatemove);
}

void GameView::keyupdatemove()

{
    if(pressedKeys.contains(Qt::Key_Left)&&pressedKeys.contains(Qt::Key_Right)){
        emit stopPlayer();

    }
    else if (pressedKeys.contains(Qt::Key_Left)) {
       emit movePlayerLeft();

    }
    else if (pressedKeys.contains(Qt::Key_Right)) {
       emit movePlayerRight();
    }
    if (!pressedKeys.contains(Qt::Key_Left)&&!pressedKeys.contains(Qt::Key_Right)) {
        emit stopPlayer();// 停止移动
    }
    /*if(pressedKeys.contains(Qt::Key_Space)){
        emit playerJump();
        emit  playerdoublejump();

    }*/
}

void GameView::gameover()
{
    this->setFocusPolicy(Qt::NoFocus);  // 禁用焦点
    this->setEnabled(false);
}

void GameView::keyPressEvent(QKeyEvent *event)
{
    pressedKeys.insert(event->key());

/*switch (event->key()) {
    case Qt::Key_Left:
        emit movePlayerLeft(); // 发射信号通知玩家左移
        break;
    case Qt::Key_Right:
        emit movePlayerRight();
        break;
    case Qt::Key_Space:
        emit playerJump();
        break;
    }
    //QGraphicsView::keyPressEvent(event);*/
    if(event->key()==Qt::Key_Space){
       // emit  playerdoublejump();
        emit playerJump();

    }

}

void GameView::keyReleaseEvent(QKeyEvent *event)
{
    pressedKeys.remove(event->key());
    /*if (!pressedKeys.contains(Qt::Key_Left)&&!pressedKeys.contains(Qt::Key_Right)) {
        emit stopPlayer();// 停止移动
    }
    //QGraphicsView::keyReleaseEvent(event);*/
}
